package bsc.war.form;



import bsc.ejb.entity.SRM;
import bsc.ejb.entity.ScoreDomain;
import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 *
 * @author memozac
 */
public class NewSRM extends AbstractController  {

     @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
         HttpServletResponse response) throws Exception {
        
        try {
            DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");
            
            boolean edit = false;
            Long idSRM = -1L;

            if (NumberUtils.isDigits(request.getParameter("idSRM"))) {
                Long id = Long.valueOf(request.getParameter("idSRM"));
                if (id >= 0) {
                    edit = true;
                    idSRM = id;
                }
            }

            SRM SRMReal = null;

            if(edit){
                SRMReal= delegate.findSRM(idSRM);
            }else{
                SRMReal = (SRM) Factory.getBean("SRM");
            }
            

            ScoreDomain scoreDomain = (ScoreDomain)request.getSession(true).getAttribute("currentScoreDomain");

            SRMReal.setName(request.getParameter("name"));
            SRMReal.setPlace(request.getParameter("place"));
            SRMReal.setResponsable(request.getParameter("responsable"));
            SRMReal.setScoreView(scoreDomain.getScoreView());
            SRMReal.setExpectedTime(Double.parseDouble(request.getParameter("expectedTime")));
            DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
            SRMReal.setSRMDate(df.parse(request.getParameter("SRMDate")));
            SRMReal.setSRMHour(request.getParameter("SRMHour"));


            if(edit){
                delegate.updateSRM(SRMReal);
            }else {
                delegate.createSRM(SRMReal);
            }
            

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Caught exception: "+e);
        }
         
         return new ModelAndView("newSRM");
    }

}
